package com.rest.demo.concurrent;

import java.util.Random;

/**
 * @author Administrator
 * @decription
 * @Date 2018-02-01 8:52
 */
public class ShareDataDemo {

    private static int data = 0;

    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int temp = new Random().nextInt();
                    System.out.println(Thread.currentThread().getName() + " has put a data: " + temp);
                    threadLocal.set(temp);
                    data = temp;

                    new TestA().getData();
                    new TestB().getData();
                }
            }).start();
        }
    }

    static class TestA {
        public void getData() {
            System.out.println("A get data from " + Thread.currentThread().getName() + ": " + threadLocal.get());
        }
    }

    static class TestB {
        public void getData() {
            System.out.println("B get data from " + Thread.currentThread().getName() + ": " + threadLocal.get());
        }
    }
}

class User {

    private static ThreadLocal<User> threadLocal = new ThreadLocal<User>();

    private String name;

    private Integer age;

    private User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public static User getInstance() {
        User user = threadLocal.get();
        if(user == null) {
            user = new User();
            threadLocal.set(user);
        }
        return user;
    }
}
